package com.property.business.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.property.business.common.Result;
import com.property.business.entity.Repair;
import com.property.business.service.IRepairService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 业务-报事报修 前端控制器
 * </p>
 *
 * @author 刘煦煌
 * @since 2023-11-24
 */
@RestController
@RequestMapping("/repair")
public class RepairController {

    @Resource
    private IRepairService repairService;

    //获取工单数据（根据状态获取）
    @GetMapping("/list/{type}")
    public Result findPage(@PathVariable Integer type) {
        type = Optional.of(type).orElse(1);
        LambdaQueryWrapper<Repair> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Repair::getCreateTime);
        wrapper.eq(Repair::getState, type);
        List<Repair> repairList = repairService.list(wrapper);
        return Result.success(repairList);
    }

    // 新增
    @PostMapping
    public Result save(@RequestBody Repair repair) {
        LocalDateTime now = LocalDateTime.now();
        StringBuffer string = new StringBuffer();
        string.append(repair.getType()).append(repair.getPriority()).append(repair.getPhone()).append(now);
        repair.setName(string.toString());
        repair.setImages(repair.getImgs().toString().replace("[", "").replace("]", ""));
        repair.setCreateTime(now);
        repair.setState(1);
        repairService.save(repair);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        repairService.removeById(id);
        return Result.success();
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        repairService.removeByIds(ids);
        return Result.success();
    }

    @GetMapping
    public Result findAll() {
        return Result.success(repairService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(repairService.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<Repair> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        return Result.success(repairService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

}

